<!-- 菜品相关组件 -->
<template>
  <div class="food-wrap" @showFullReturnFoodDialog="handleShowFullReturnFood">
    <div
      class="food-wrap"
      :class="{ fullWidth: currentDeskDetail ? false : true }"
      v-if="currentDeskDetail"
    >
      <!-- 桌台锁定蒙层（覆盖整个内容区域） -->
      <div v-if="currentDeskDetail?.is_lock?.value === 1" class="global-lock-mask" @click.stop>
        <div class="lock-content">
          <div class="lock-text">桌台已锁定</div>
          <div class="unlock-btn" @click.stop="handleUnlockDesk">解锁</div>
        </div>
      </div>
      <!-- 桌台和用户信息 -->
      <div class="food-box-left">
        <div class="title-box">
          <div class="numberAndDesc">
            <el-tooltip
              class="item"
              effect="dark"
              :content="currentDeskDetail.desk_name"
              placement="top"
            >
              <div
                class="number"
                :class="currentDeskDetail.desk_name.length > 6 ? 'number-less-size' : ''"
              >
                {{ currentDeskDetail.desk_name }}
              </div>
            </el-tooltip>
            <!-- 桌台区域信息（暂时注释，后续可能需要） -->
            <!-- <el-tooltip
              v-if="currentDeskDetail.desk && currentDeskDetail.desk.region"
              class="item"
              effect="dark"
              :content="currentDeskDetail.desk.region.name"
              placement="top"
            >
              <div class="desc">桌/{{ currentDeskDetail.desk.region.name }}</div>
            </el-tooltip> -->
          </div>
          <div class="member-people-box">
            <!-- 会员信息 -->
            <div class="member" @click.stop="onClickBindMember">
              <el-tooltip
                v-if="currentDeskDetail.user && currentDeskDetail.user.grade"
                class="item"
                effect="dark"
                :content="`会员：${currentDeskDetail.user.real_name}`"
                placement="top"
              >
                <div class="name">会员：{{ currentDeskDetail.user.real_name }}</div>
              </el-tooltip>
              <div class="name" v-else>绑定会员</div>
              <img class="icon" src="@/assets/images/home/edit-icon.png" alt="" />
            </div>
            <!-- 用餐人数 -->
            <div class="people" @click.stop="onClickEditUseNum">
              <el-tooltip
                class="item"
                effect="dark"
                :content="`人数：${currentDeskDetail.use_num}/${currentDeskDetail.desk.capacity}`"
                placement="top"
              >
                <div class="name">
                  人数：{{ currentDeskDetail.use_num }}/{{ currentDeskDetail.desk.capacity }}
                </div>
              </el-tooltip>
              <img class="icon" src="@/assets/images/home/edit-icon.png" alt="" />
            </div>
          </div>
        </div>
        <!-- 订单号信息 -->
        <div
          class="order-number-box"
          v-if="
            currentDeskDetail && currentDeskDetail.order_id && currentDeskDetail.order_id != '0'
          "
        >
          <div class="number">订单号：{{ currentDeskDetail.order_id }}</div>
          <div class="discount-btn" @click.stop="handleOpenFoodPriceDialog">修改菜品价格</div>
        </div>
        <!-- 菜品滚动列表 -->
        <div
          class="food-scroll-list"
          v-if="!isEmpty(currentDeskDetail && currentDeskDetail.foodList)"
        >
          <div
            class="scroll-list-item"
            :class="{ 'scroll-list-item-active': selectFoodActiveIndex === index }"
            v-for="(item, index) in currentDeskDetail.foodList"
            :key="item.id"
            @click.stop="handleSelectFood(index, item)"
          >
            <div class="number">
              {{ index >= 10 ? index : '0' + (index + 1) }}
            </div>
            <!-- 酒席点菜 -->
            <div class="desc-box" v-if="index === 0 && !isEmpty(item.feastFoodList)">
              <div class="name-box">
                <div
                  v-if="item.status"
                  :style="{ background: foodBgStatus[item.status.value] }"
                  class="tag"
                >
                  {{ foodTextStatus[item.status.value] }}
                </div>
                <div class="name">
                  <el-tooltip effect="dark" content="酒席" placement="top">
                    <span>酒席</span>
                  </el-tooltip>
                </div>
                <!-- VIP会员价图标 -->
                <img
                  class="vip-icon"
                  src="@/assets/images/home/vip-icon-gold.png"
                  alt=""
                  v-if="currentDesktopDiscountInfo && currentDesktopDiscountInfo.is_vip_price === 1"
                />
                <!-- 是否赠送标识（暂时注释，后续可能需要） -->
                <!-- <div
                      v-if="item.is_present.value === 1 || item.is_present.value === 2"
                      class="gift-btn"
                    >
                      赠品
                    </div> -->
                <!-- 打印状态标识（暂时注释，后续可能需要） -->
                <!-- <div class="print-btn" v-if="item.print === 1">打印</div> -->
              </div>
              <div class="price-box">
                <!-- 原价信息（暂时注释，后续可能需要） -->
                <!-- <div class="orginPrice">
                      <div>￥{{ item.model_price }}</div>
                      <span v-if="item.model_discount !== 10 && item.model_discount !== 0"
                        >×{{ item.model_discount }}折</span
                      >
                    </div> -->
                <div class="count">￥{{ item.banquetMoney }}</div>
                <!-- 酒席副桌显示1席即可 -->
                <div class="count" v-if="currentDeskDetail.target_record_id > 0">x1席</div>
                <!-- 酒席主桌显示全部席数 -->
                <div class="count" v-else-if="item.banquetOpenNum !== 1">
                  ×{{ item.banquetOpenNum }}席
                </div>
                <div class="discount-price">￥{{ item.banquetTotalMoney }}</div>
              </div>
              <div class="info-box">
                <div class="sku">
                  <!-- 规格信息（暂时注释，后续可能需要） -->
                  <!-- <el-tooltip
                        v-if="dealFoodSkuDescFun(item)"
                        effect="dark"
                        :content="dealFoodSkuDescFun(item)"
                        placement="top"
                      >
                        <span>{{ dealFoodSkuDescFun(item) }}</span>
                      </el-tooltip> -->
                </div>
                <div class="time">
                  <div v-if="item.banquetClerkName">{{ item.banquetClerkName }}</div>
                  <span>{{ item.banquetCreateTime }}</span>
                </div>
              </div>
              <!-- 显示酒席下面的菜品 -->
              <div
                class="group-food-list"
                v-if="!isEmpty(item.feastFoodList) && selectFoodActiveIndex === index"
              >
                <div
                  class="group-food-list-item"
                  v-for="food in item.feastFoodList"
                  :key="food.food_sku_id"
                >
                  <el-tooltip effect="dark" :content="food.name" placement="top">
                    <div class="name">{{ food.name }}</div>
                  </el-tooltip>
                  <div class="count">
                    ×{{ food.num
                    }}<span v-if="food.skuInfo && food.skuInfo.unit">{{ food.skuInfo.unit }}</span>
                  </div>
                  <div class="count">x{{ food.desk_num }}席</div>
                </div>
              </div>
            </div>
            <!-- 非酒席点菜 -->
            <div class="desc-box" v-if="isEmpty(item.feastFoodList)">
              <div class="name-box">
                <div
                  v-if="item.status"
                  :style="{ background: foodBgStatus[item.status.value] }"
                  class="tag"
                >
                  {{ foodTextStatus[item.status.value] }}
                </div>
                <div class="name">
                  <el-tooltip effect="dark" :content="item.name" placement="top">
                    <span>{{ item.name }}</span>
                  </el-tooltip>
                </div>
                <!-- VIP会员价图标 -->
                <img
                  class="vip-icon"
                  src="@/assets/images/home/vip-icon-gold.png"
                  alt=""
                  v-if="currentDesktopDiscountInfo && currentDesktopDiscountInfo.is_vip_price === 1"
                />
                <!-- 是否赠送标识 -->
                <div v-if="item.is_present === 1 || item.is_present === 2" class="gift-btn">
                  赠品
                </div>
                <!-- 打印状态标识 -->
                <div class="print-btn" v-if="item.print === 1">打印</div>
                <div class="print-btn" v-else>不打印</div>
              </div>
              <div class="price-box">
                <div class="orginPrice">
                  <!-- 显示会员价 -->
                  <div
                    style="color: #efc291"
                    v-if="
                      currentDesktopDiscountInfo && currentDesktopDiscountInfo.is_vip_price === 1
                    "
                  >
                    <!-- 手写菜品 -->
                    <span v-if="item.is_write_food == 1"> ￥{{ item.member_price }} </span>
                    <!-- 非手写菜品 -->
                    <span v-else> ￥{{ item.skuInfo.member_price }} </span>
                  </div>
                  <!-- 显示非会员价 -->
                  <div v-else>
                    <!-- 手写菜品 -->
                    <span v-if="item.is_write_food == 1"> ￥{{ item.price }} </span>
                    <!-- 非手写菜品 -->
                    <span v-else> ￥{{ item.skuInfo.price }} </span>
                  </div>
                  <!-- 折扣类型discount_type:(0:无折扣 1:单品折扣 2:整单折扣 3:会员折扣) -->
                  <span v-if="item.discount_type === 3 && item.member_discount !== 10"
                    >×{{ item.member_discount }}折</span
                  >
                  <span v-else-if="item.discount_type === 2 && item.order_discount !== 10"
                    >×{{ item.order_discount }}折</span
                  >
                  <span v-else-if="item.discount_type === 1 && item.discount !== 10"
                    >×{{ item.discount }}折</span
                  >
                </div>
                <div class="count">
                  ×{{ item.num
                  }}<span v-if="item.skuInfo && item.skuInfo.unit">{{ item.skuInfo.unit }}</span>
                </div>
                <div
                  class="count"
                  v-if="
                    currentDeskDetail.open_type.value === 50 &&
                    currentDeskDetail.open_num > 1 &&
                    (currentDeskDetail.target_record_id === 0 ||
                      currentDeskDetail.target_record_id === '0')
                  "
                >
                  ×{{ item.desk_num }}席
                </div>
                <div class="discount-price">￥{{ item.total_money }}</div>
              </div>
              <div class="info-box">
                <div class="sku">
                  <el-tooltip
                    v-if="dealFoodSkuDescFun(item)"
                    effect="dark"
                    :content="dealFoodSkuDescFun(item)"
                    placement="top"
                  >
                    <span>{{ dealFoodSkuDescFun(item) }}</span>
                  </el-tooltip>
                </div>
                <div class="time">
                  <div v-if="item.clerk_name">{{ item.clerk_name }}</div>
                  <span>{{ item.create_time }}</span>
                </div>
              </div>
              <!-- 菜品操作按钮 -->
              <div class="btn-list" v-show="selectFoodActiveIndex === index">
                <div class="btn-item" @click.stop="handleFoodAction(1)">催菜</div>
                <div class="btn-item" @click.stop="handleShowWaitFood" v-if="item.status.value !== 3">等叫</div>
                <div class="btn-item" @click.stop="handleShowFoodSeatsDialog(item, emit)" v-if="item.status.value === 3">起菜</div>
                <div class="btn-item" @click.stop="handleShowBackFood">退菜</div>
                <!-- 是否赠送(0:不赠送，2：部分赠送  1:单品全部赠送) -->
                <div class="btn-item" @click.stop="handleShowGiftFood">
                  {{ item.is_present === 1 || item.is_present === 2 ? '撤赠' : '赠送' }}
                </div>
                <div class="btn-item" @click.stop="handleShowDiscountFood">打折</div>
              </div>
              <!-- 显示套餐下面的菜品 -->
                <div
                class="group-food-list"
                v-if="
                  !isEmpty(groupFoodList) && item.is_group === 1 && selectFoodActiveIndex === index
                "
              >
                <div
                  class="group-food-list-item"
                  v-for="group in groupFoodList"
                  :key="group.food_id"
                >
                  <el-tooltip effect="dark" :content="group.name" placement="top">
                    <div class="name" style="width: 1rem">
                      {{ group.name }}
                    </div>
                  </el-tooltip>

                  <div class="element-input-box">
                    <!-- {{ group.num }} -->
                    <!-- <el-input-number
                      class="element-input-inner"
                      v-model=""
                      step-strictly
                      :min="0"
                      disabled
                      @change="handleFoodNumberChange($event, item, group)"
                    ></el-input-number> -->
                  </div>
                  <div class="count">x{{ group.num }}{{ group.sku.unit }}</div>
                  <!-- 显示会员价 -->
                  <div
                    v-if="
                      currentDesktopDiscountInfo && currentDesktopDiscountInfo.is_vip_price === 1
                    "
                    class="money"
                  >
                    ￥{{ group.sku.member_price }}
                  </div>
                  <!-- 显示原价 -->
                  <div v-else class="money">￥{{ group.sku.price }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 暂无数据的组件 -->
        <div class="no-data-box" v-if="isEmpty(currentDeskDetail && currentDeskDetail.foodList)">
          <NotData desc="暂无菜品，请先操作点菜" />
        </div>
        <!-- 结算信息 -->
        <div class="settlement-content" v-if="currentDeskDetail && currentDeskDetail.orderInfo">
          <template
            v-if="
              (currentDeskDetail && !isEmpty(currentDeskDetail.foodList)) ||
              !isEmpty(currentDeskDetail && currentDeskDetail.feastFoodList)
            "
          >
            <div class="count">
              <span> 数量：{{ currentDeskDetail.orderInfo.food_num }}份 </span>
              <span>服务费：￥{{ currentDeskDetail.orderInfo.service_money || 0 }}</span>
            </div>
            <div class="price-box">
              <div class="total-price">
                总金额：￥{{ currentDeskDetail.orderInfo.model_money }}，优惠：￥{{
                  currentDeskDetail.orderInfo.total_discount_money
                }}
              </div>
              <div class="actual-price">
                <span>应付金额：</span>
                <div>￥{{ currentDeskDetail.orderInfo.pay_money }}</div>
              </div>
            </div>
          </template>
          <div class="btn-list">
            <div class="btn-item" @click.stop="handleOpenMoreFeaturesAction">更多功能</div>
            <div class="btn-item" @click.stop="handleOpenPreSettlementDialog">
              <span> {{ currentDeskDetail.is_lock.value === 2 ? '已预结' : '预结' }}</span>
            </div>
            <div class="btn-item" @click.stop="handleOpenBusinessStatementDialog">账单</div>
            <div class="btn-item" @click.stop="handleOpenFoodAdjustmentMoneyDialog">调整零头</div>
          </div>
          <div class="settlement-btn" @click.stop="handleOpenSettlementDialog">结算</div>
        </div>
      </div>
      <!-- 操作按钮 -->
      <div class="food-box-right">
        <div class="button-list">
          <div
            class="button-item-content"
            v-for="(item, index) in actionsRenderList"
            :key="item.name + index"
          >
            <div
              v-if="index === 0"
              class="button-item-active"
              @click.stop="
                handleActionBar(
                  index,
                  currentDeskDetail,
                  selectFoodActiveIndex,
                  actionsRenderList,
                  emit
                )
              "
            >
              <span>{{ item.name }}</span>
              <img src="@/assets/images/diancai-icon.png" alt="" />
            </div>
            <div
              v-else
              class="button-item"
              :class="{
                'button-item-disabled':
                  (item.needSelectFood && selectFoodActiveIndex === -1) || item.disabled
              }"
              @click.stop="
                !item.disabled &&
                handleActionBar(
                  index,
                  currentDeskDetail,
                  selectFoodActiveIndex,
                  actionsRenderList,
                  emit
                )
              "
            >
              {{ item.name }}
            </div>
          </div>
        </div>

        <!-- 右侧内容：做法面板（参考老项目右侧切页，不使用弹框） -->
        <!-- <PracticeFoodPanel
          v-if="showFoodPracticeDialog"
          :deskDetail="currentDeskDetail"
          :selectFoodActiveIndex="selectFoodActiveIndex"
          @refreshData="emit('refreshData')"
          @close="showFoodPracticeDialog = false"
        /> -->
      </div>
      <!-- 暂无数据的组件 -->
      <!-- <div class="no-data-box" v-else>
        <NotData desc="请先在右侧选择对应的桌台" />
      </div> -->
    </div>

    <!-- 全单等叫弹框 -->
    <FullWaitDialog
      v-model="showWaitDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 单品等叫弹框 -->
    <WaitFood
      v-model="showFoodWaitDialog"
      :deskDetail="currentDeskDetail"
      :selectFoodActiveIndex="selectFoodActiveIndex"
      @refreshData="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 单品退菜弹框 -->
    <BackFood
      v-model="showFoodBackDialog"
      :deskDetail="currentDeskDetail"
      :selectFoodActiveIndex="selectFoodActiveIndex"
      @refreshData="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 全单退菜弹框 -->
    <FullReturnFoodDialog
      v-model="showFullReturnFoodDialog"
      :deskDetail="currentDeskDetail"
      @refreshData="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 单品赠送弹框 -->
    <GiftFood
      v-model="showFoodGiftDialog"
      :deskDetail="currentDeskDetail"
      :selectFoodActiveIndex="selectFoodActiveIndex"
      @refreshData="emit('refreshData')"
    />

    <!-- 单品打折弹框 -->
    <DiscountFood
      v-model="showFoodDiscountDialog"
      :deskDetail="currentDeskDetail"
      :selectFoodActiveIndex="selectFoodActiveIndex"
      @refreshData="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 单品做法弹框 -->
    <!-- <PracticeFood
      v-model="showFoodPracticeDialog"
      :deskDetail="currentDeskDetail"
      :selectFoodActiveIndex="selectFoodActiveIndex"
      @refreshData="emit('refreshData')"
    /> -->

    <!-- 全单赠送弹框 -->
    <FullGiftDialog
      v-model="showGiftDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />
    <!-- 菜品转台弹框 -->
    <FoodTransferDialog
      v-model="showTransferDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 规格/数量 弹框（只查询与UI，不提交） -->
    <SpecificationQuantityDialog
      v-model="showSpecQuantityDialog"
      :current-food-data="specFoodData"
      @confirm="payload => onSpecConfirm(payload, emit)"
      :loading="specQuantityLoading"
    />

    <!-- 菜品价格弹框 -->
    <FoodPriceDialog
      v-model="showFoodPriceDialog"
      :current-food="
        selectFoodActiveIndex !== -1 ? currentDeskDetail.foodList[selectFoodActiveIndex] : null
      "
      @success="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 会员绑定弹框 -->
    <MemberBindDialog
      v-model:modelValue="showMemberDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
    />

    <!-- 全单打折 -->
    <FullOrderDiscountDialog
      v-model="showFullDiscountDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 修改人数 -->
    <DinerDialog
      v-model="showDinerDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 调整零头弹窗 -->
    <FoodAdjustmentMoneyDialog
      v-model="showFoodAdjustmentMoneyDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
      @refreshDesk="emit('refreshDesk')"
    />

    <!-- 账单弹窗 -->
    <BusinessStatementDialog
      v-model="showBusinessStatementDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
    />

    <!-- 预结账弹窗 -->
    <PreSettlementDialog
      v-model="showPreSettlementDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
       @refreshDesk="emit('refreshDesk')"
    />

    <!-- 结算弹窗 -->
    <SettlementDialog
      v-model:showDialog="showSettlementDialog"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
    />

    <!-- 更多功能侧边栏 -->
    <MoreFeaturesAction
      v-model="showMoreFeaturesAction"
      :desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
    />

    <!-- 手写菜品弹框 -->
    <HandwritingFoodDialog
      v-model="showHandwritingFoodDialog"
      :desk-detail="currentDeskDetail"
      @confirm="(handwritingFoodData) => addHandwritingFood(handwritingFoodData, currentDeskDetail, emit)"
    />

    <!-- 菜品席数弹框 -->
    <FoodSeatsDialog
      :visible="showFoodSeatsDialog"
      @update:visible="showFoodSeatsDialog = $event"
      :select-current-food-data="currentDeskDetail?.foodList[selectFoodActiveIndex]"
      :current-desk-detail="currentDeskDetail"
      @success="emit('refreshData')"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted } from 'vue'
import { isEmpty } from '@/utils/toolsValidate'
import { ElMessage } from 'element-plus'
import { deskLockDesk } from '@/api/desktop'
import MessageTips from '@/components/messageTips'
import { FOOD_BG_STATUS, FOOD_TEXT_STATUS } from '@/constants/foodStatus'
import { bus } from '@/utils/bus'
import { useFoodActions } from './hook/useFoodActions'
import { useSingleFoodActions } from './hook/useSingleFoodActions'
import FullWaitDialog from './components/FullWaitDialog.vue'
import FullGiftDialog from './components/FullGiftDialog.vue'
import FoodTransferDialog from './components/FoodTransferDialog.vue'
import WaitFood from './SignleFoodAction/WaitFood.vue'
import BackFood from './SignleFoodAction/BackFood.vue'
import FullReturnFoodDialog from './components/FullReturnFoodDialog.vue'
import GiftFood from './SignleFoodAction/GiftFood.vue'
import DiscountFood from './SignleFoodAction/DiscountFood.vue'
import PracticeFoodPanel from './SignleFoodAction/PracticeFoodPanel.vue'
import SpecificationQuantityDialog from '../common/SpecificationQuantityDialog.vue'
import FullOrderDiscountDialog from './components/FullOrderDiscountDialog.vue'
import DinerDialog from './components/DinerDialog.vue'
import MemberBindDialog from './components/MemberBindDialog.vue'
import FoodPriceDialog from './components/FoodPriceDialog.vue'
import FoodAdjustmentMoneyDialog from './components/FoodAdjustmentMoneyDialog.vue'
import BusinessStatementDialog from './components/BusinessStatementDialog.vue'
import PreSettlementDialog from './components/PreSettlementDialog.vue'
import SettlementDialog from './components/SettlementDialog.vue'
import MoreFeaturesAction from './MoreFeaturesAction/Index.vue'
import NotData from '@/components/NotData/Index.vue'
import HandwritingFoodDialog from '@/views/Diancai/components/HandwritingFoodDialog.vue'
import FoodSeatsDialog from './components/FoodSeatsDialog/Index.vue'
import { useRoute } from 'vue-router'

const route = useRoute()
// 从父组件接收当前选中的桌台详情
const props = defineProps<{ deskDetail: any | null }>()

interface Emits {
  (e: 'refreshData'): void
  (e: 'refreshDesk'): void
  (e: 'openPractice'): void
}
// 定义emit事件
const emit = defineEmits<Emits>()

// 绑定会员
const onClickBindMember = async () => {
  showMemberDialog.value = true
}

// 修改用餐人数
const onClickEditUseNum = async () => {
  showDinerDialog.value = true
}

// 修改人数弹框
const showDinerDialog = ref(false)
const showMemberDialog = ref(false)
const showFoodPriceDialog = ref(false)
const showFoodAdjustmentMoneyDialog = ref(false)
const showBusinessStatementDialog = ref(false)
const showPreSettlementDialog = ref(false)
const showSettlementDialog = ref(false)
const showMoreFeaturesAction = ref(false)
const showFoodWaitDialog = ref(false)
const showFoodBackDialog = ref(false)
const showFoodGiftDialog = ref(false)
const showFoodDiscountDialog = ref(false)

// 使用右侧菜品操作hook
const {
  handleActionBar,
  getActionsRenderList,
  showWaitDialog,
  showGiftDialog,
  showTransferDialog,
  showSpecQuantityDialog,
  specFoodData,
  onSpecConfirm,
  specQuantityLoading,
  showFullDiscountDialog,
  showFullReturnFoodDialog,
  showHandwritingFoodDialog,
  addHandwritingFood,
  showFoodSeatsDialog,
  handleShowFoodSeatsDialog
} = useFoodActions()

// 使用单品操作hook
const { handleSingleFoodHurry } = useSingleFoodActions()

// 当前桌台详情
const currentDeskDetail = computed(() => props.deskDetail)
// 动态按钮渲染列表（根据桌台状态切换文案）
const actionsRenderList = computed(() => getActionsRenderList(currentDeskDetail.value || {}))
// 选中的菜品索引
const selectFoodActiveIndex = ref(-1)
// 当前菜品套餐详情数据下面的菜品列表
const groupFoodList = ref<any[]>([])
// 当前桌台优惠信息数据
const currentDesktopDiscountInfo = computed(() => {
  console.log('props.deskDetail', props.deskDetail)

  return {
    is_vip_price: props.deskDetail?.is_vip
  }
})
// 区分目前跳转的页面，【账单，预结】
const routeToPage = ref('')

// 菜品状态背景色
const foodBgStatus = FOOD_BG_STATUS

// 菜品状态文字
const foodTextStatus = FOOD_TEXT_STATUS

// 处理回显菜品的规格信息（做法+口味+部位）
const dealFoodSkuDescFun = (item: any) => {
  // 处理手写做法
  let writeMakingList: string[] = []
  if (!isEmpty(item.write_making)) {
    writeMakingList = item.write_making.map((val: any) => val.name)
  }
  // 所有规格信息进行合并
  const skuInfoList = [
    ...(item.making_names || []),
    ...writeMakingList,
    ...(item.taste_names || []),
    ...(item.write_taste || []),
    ...(item.position || [])
  ]
  if (!isEmpty(skuInfoList)) {
    return skuInfoList.join('/')
  } else {
    return false
  }
}

// 处理打开弹框
const handleActionOpenDialog = (dialogType: string) => {
  console.log('打开弹框:', dialogType)
  // TODO: 实现弹框打开逻辑
  ElMessage.info(`打开${dialogType}弹框`)
}

// 处理显示等叫弹窗
const handleShowWaitFood = () => {
  showFoodWaitDialog.value = true
}


// 处理显示退菜弹窗
const handleShowBackFood = () => {
  showFoodBackDialog.value = true
}

// 处理显示全单退菜弹窗
const handleShowFullReturnFood = (deskDetail: any) => {
  showFullReturnFoodDialog.value = true
}

// 处理显示赠送弹窗
const handleShowGiftFood = () => {
  showFoodGiftDialog.value = true
}

// 处理显示打折弹窗
const handleShowDiscountFood = () => {
  showFoodDiscountDialog.value = true
}

// 处理打开菜品价格弹框
const handleOpenFoodPriceDialog = () => {
  if (selectFoodActiveIndex.value === -1) {
    ElMessage.warning('请先选择菜品')
    return
  }
  showFoodPriceDialog.value = true
}

// 处理打开调整零头弹框
const handleOpenFoodAdjustmentMoneyDialog = () => {
  showFoodAdjustmentMoneyDialog.value = true
}

// 处理打开账单弹框
const handleOpenBusinessStatementDialog = () => {
  showBusinessStatementDialog.value = true
}

// 处理打开预结账弹框
const handleOpenPreSettlementDialog = () => {
  showPreSettlementDialog.value = true
}

// 处理打开结算弹框
const handleOpenSettlementDialog = () => {
  // 检查是否有菜品
  if (isEmpty(currentDeskDetail.value?.foodList)) {
    ElMessage.warning('请先点菜后再进行结算')
    return
  }

  // 检查菜品是否全部上齐
  const hasUnfinishedFood = currentDeskDetail.value?.foodList?.some((food: any) => {
    // 检查菜品状态，如果状态不是已上菜(status.value === 4)，则认为未上齐
    // 状态说明：0:待确认 1:起 2:催 3:等 4:上(已上菜) 5:退
    return food.status && food.status.value !== 4
  })

  if (hasUnfinishedFood) {
    ElMessage.warning('菜品尚未全部上齐，请等待上齐后再进行结算')
    return
  }

  showSettlementDialog.value = true
}

// 处理打开更多功能弹框
const handleOpenMoreFeaturesAction = () => {
  showMoreFeaturesAction.value = true
}

// 解锁桌台
const handleUnlockDesk = async () => {
  try {
    if (!currentDeskDetail.value?.id) {
      ElMessage.warning('无效桌台，无法解锁')
      return
    }

    const deskName =
      currentDeskDetail.value?.desk_name ||
      currentDeskDetail.value?.recordInfo?.desk_name ||
      currentDeskDetail.value?.name ||
      '未知桌台'

    const messageTipsInstance = await MessageTips.message(
      {
        title: '解锁桌台',
        content: `确定要解锁桌台 ${deskName} 吗？`,
        isOnCancel: true,
        onCancelText: '取消',
        onSumbitText: '确定'
      },
      async () => {
        try {
          messageTipsInstance.setLoading(true)
          const res = await deskLockDesk({ record_id: currentDeskDetail.value.id })
          if (res.status === 200) {
            ElMessage.success('解锁成功')
            emit('refreshDesk')
            emit('refreshData')
            messageTipsInstance.close()
          } else {
            ElMessage.error('解锁失败')
            messageTipsInstance.setLoading(false)
          }
        } catch (error) {
          console.error('解锁失败:', error)
          ElMessage.error('解锁失败')
          messageTipsInstance.setLoading(false)
        }
      }
    )
  } catch (error) {
    console.error('打开解锁确认弹窗失败:', error)
  }
}

// 处理选择菜品
const handleSelectFood = (index: number, item: any) => {
  selectFoodActiveIndex.value = index
  console.log('选择菜品:', item)

  // 如果是套餐，就请求套餐详情数据来展示套餐下面的所有菜品
  if (item.is_group === 1 && item.foodgroup_info) {
    // 先重置
    groupFoodList.value = []
    let dataList: any[] = []
    item.foodgroup_info.forEach((food: any) => {
      dataList = [...dataList, ...food.foodList]
    })
    // 再获取
    groupFoodList.value = dataList.filter(item => item.num !== 0)
  }
}

// 菜品操作相关
const handleFoodAction = (index: number) => {
  handleSingleFoodHurry(currentDeskDetail.value, emit, selectFoodActiveIndex.value)
}



// 进行页面跳转和打开弹窗的相关判断
const routeToPath = (type: string) => {
  console.log('页面跳转:', type)
  ElMessage.info(`页面跳转: ${type}`)
}

// 处理桌台变动刷新事件
const handleDeskRefresh = () => {
  // 刷新菜品数据和桌台数据
  emit('refreshData')
  emit('refreshDesk')
}
// 刷新菜品变化
const handleFoodListRefresh = (data: any) => {
  console.log('刷新菜品变化:', data)
  let id = route.params.id
  if (data.detail.record_id === id) {
    emit('refreshData')
  }
}


onMounted(() => {
  // 监听桌台变动事件，自动刷新菜品数据
  bus.on('desk-list-refresh', handleFoodListRefresh)
})

onUnmounted(() => {
  // 移除事件监听
  bus.off('desk-list-refresh', handleFoodListRefresh)
})
</script>

<style lang="scss" scoped>
.fullWidth {
  width: 726px !important;
  transition: all 1s !important;
}

.food-wrap {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  width: 726px;
  min-height: 986px;
  box-sizing: border-box;
  background: #ffffff;
  border-radius: 20px;
  transition: all 1s !important;

  position: relative;

  .global-lock-mask {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 50;
    display: flex;
    align-items: center;
    justify-content: center;

    .lock-content {
      background: #ffffff;
      border-radius: 12px;
      padding: 24px 32px;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

      .lock-text {
        font-size: 18px;
        color: #333333;
        margin-bottom: 16px;
        font-weight: 700;
      }

      .unlock-btn {
        width: 120px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #ffffff;
        border: 1px solid #7c0a03;
        color: #7c0a03;
        border-radius: 12px;
        cursor: pointer;
      }

      .unlock-btn:hover {
        background: #7c0a03;
        color: #ffffff;
      }
    }
  }

  .food-box-left {
    position: relative;
    width: 546px;
    height: 986px;
    box-sizing: border-box;
    transition: all 1s !important;

    .lock-mask {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 20;
      display: flex;
      align-items: center;
      justify-content: center;

      .lock-content {
        background: #ffffff;
        border-radius: 12px;
        padding: 24px 32px;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

        .lock-text {
          font-size: 18px;
          color: #333333;
          margin-bottom: 16px;
          font-weight: 700;
        }

        .unlock-btn {
          width: 120px;
          height: 40px;
          line-height: 40px;
          text-align: center;
          background: #ffffff;
          border: 1px solid #7c0a03;
          color: #7c0a03;
          border-radius: 12px;
          cursor: pointer;
        }

        .unlock-btn:hover {
          background: #7c0a03;
          color: #ffffff;
        }
      }
    }

    .title-box {
      padding: 12px 24px;
      display: flex;
      align-items: flex-end;
      justify-content: space-between;
      box-sizing: border-box;

      .numberAndDesc {
        display: flex;
        align-items: flex-end;
        margin-right: 24px;

        .number {
          font-size: 30px;
          font-family:
            PingFang SC,
            PingFang SC-Bold;
          font-weight: 700;
          text-align: left;
          color: #333333;
        }

        .number-less-size {
          font-size: 28px !important;
        }

        .desc {
          font-size: 18px;
          max-width: 100px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #333333;
          position: relative;
          top: -4px;
        }
      }

      .member-people-box {
        display: flex;
        align-items: center;

        .member {
          display: flex;
          align-items: center;
          cursor: pointer;

          .name {
            max-width: 130px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 18px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            color: #333333;
          }

          .icon {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            margin-left: 12px;
          }
        }

        .people {
          display: flex;
          align-items: center;
          cursor: pointer;
          margin-left: 30px;

          .name {
            max-width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 18px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            color: #333333;
          }

          .icon {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            margin-left: 12px;
          }
        }
      }
    }

    .order-number-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 21px 32px 21px 24px;
      box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.04);
      border-top: 1px solid #e2e2e2;

      .number {
        font-size: 16px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
      }

      .discount-btn {
        width: 120px;
        height: 40px;
        line-height: 40px;
        background: #ffffff;
        border: 1px solid #999999;
        border-radius: 12px;
        font-size: 16px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #666666;
        cursor: pointer;
      }

      .discount-btn:hover {
        border-color: rgb(124, 10, 3);
        color: rgb(124, 10, 3);
      }
    }

    //滚动条整体的大小
    .food-scroll-list::-webkit-scrollbar {
      width: 6px;
      height: 0;
    }

    //滚动条里滑动的滑块
    .food-scroll-list::-webkit-scrollbar-thumb {
      height: 200px;
      background: #d2d2d2;
      border-radius: 3px;
    }

    //滚动条底层样式
    .food-scroll-list::-webkit-scrollbar-track {
      display: none;
    }

    .food-scroll-list {
      height: 606px;
      box-sizing: border-box;
      overflow-y: auto;
      transition: all 1s;
      padding-bottom: 40px;


      .scroll-list-item {
        padding: 20px 30px 20px 24px;
        display: flex;
        align-items: flex-start;
        border-bottom: 1px solid #e2e2e2;
        cursor: pointer;

        .number {
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Bold;
          font-weight: 700;
          color: #666666;
          margin-right: 12px;
        }

        .desc-box {
          flex: 1;

          .name-box {
            display: flex;
            align-items: center;

            .tag {
              display: inline-block;
              padding: 0 6px;
              height: 20px;
              background: #feb101;
              border-radius: 6px;
              font-size: 12px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              text-align: center;
              line-height: 20px;
              color: #ffffff;
              margin-right: 10px;
            }

            .name {
              font-size: 18px;
              font-family:
                PingFang SC,
                PingFang SC-Bold;
              font-weight: 700;
              color: #333333;
              margin-right: 10px;
              max-width: 250px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .vip-icon {
              flex-shrink: 0;
              width: 24px;
              height: 24px;
              margin-right: 10px;
            }

            .gift-btn {
              width: 40px;
              height: 23px;
              line-height: 23px;
              border: 1px solid #ff827a;
              border-radius: 6px;
              font-size: 12px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              text-align: center;
              color: #ff827a;
              margin-right: 10px;
              cursor: pointer;
            }

            .print-btn {
              width: 52px;
              height: 23px;
              line-height: 23px;
              border: 1px solid #999999;
              border-radius: 6px;
              font-size: 12px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              text-align: center;
              color: #999999;
              cursor: pointer;
            }
          }

          .price-box {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 12px;

            .orginPrice {
              display: flex;
              align-items: center;

              > div {
                font-size: 16px;
                font-family:
                  PingFang SC,
                  PingFang SC-Regular;
                font-weight: 400;
                color: #333333;
              }

              > span {
                margin-left: 12px;
                font-size: 16px;
                font-family:
                  PingFang SC,
                  PingFang SC-Regular;
                font-weight: 400;
                color: #b60112;
              }
            }

            .count {
              font-size: 16px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              color: #333333;
            }

            .discount-price {
              font-size: 16px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              color: #333333;
            }
          }

          .info-box {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 12px;

            .sku {
              font-size: 14px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              color: #999999;
              max-width: 250px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .time {
              display: flex;
              align-items: center;
              font-size: 14px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              color: #999999;

              > div {
                margin-right: 26px;
              }
            }
          }

          .btn-list {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 20px;

            .btn-item {
              width: 80px;
              height: 40px;
              line-height: 40px;
              background: #ffffff;
              border: 1px solid #999999;
              border-radius: 12px;
              font-size: 16px;
              font-family:
                PingFang SC,
                PingFang SC-Regular;
              font-weight: 400;
              text-align: center;
              color: #333333;
              cursor: pointer;
            }

            .btn-item:hover {
              color: #7c0a03;
              border: 1px solid #7c0a03;
            }
          }

          .group-food-list {
            border-top: 1px dashed #7c0a03;
            margin-top: 20px;

            .group-food-list-item {
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-top: 12px;

              .name {
                width: 60px;
                font-size: 16px;
                font-family:
                  PingFang SC,
                  PingFang SC-Bold;
                font-weight: 700;
                color: #333333;
                max-width: 300px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              .count {
                font-size: 16px;
                font-family:
                  PingFang SC,
                  PingFang SC-Regular;
                font-weight: 400;
                color: #333333;
              }

              .money {
                width: 40px;
                font-size: 16px;
                font-family:
                  PingFang SC,
                  PingFang SC-Regular;
                font-weight: 400;
                color: #333333;
              }
              .element-input-box {
                .element-input-inner {
                  width: 134px;
                }
              }
            }
          }
        }
      }

      .scroll-list-item:last-child {
        border-bottom: none;
      }

      .scroll-list-item-active {
        background: #f4f4f4;
      }
    }

    .settlement-content {
      position: absolute;
      left: 0;
      bottom: 0;
      box-sizing: border-box;
      background: #ffffff;
      box-shadow: 0px -4px 6px 0px rgba(0, 0, 0, 0.04);
      padding: 20px;
      border-radius: 0 0 20px 20px;

      .count {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 16px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
      }

      .price-box {
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
        margin-top: 10px;

        .total-price {
          font-size: 16px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #333333;
        }

        .actual-price {
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #333333;
          display: flex;
          align-items: flex-end;

          > div {
            font-size: 24px;
            font-family:
              PingFang SC,
              Bold;
            font-weight: 700;
            color: #7c0a03;
          }
        }
      }

      .btn-list {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 20px;

        .btn-item {
          display: inline-block;
          padding: 0 16px;
          height: 44px;
          background: #ffffff;
          border: 1px solid #333333;
          border-radius: 12px;
          line-height: 44px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #333333;
          cursor: pointer;
        }

        .btn-item:hover {
          border-color: rgb(124, 10, 3);
          color: rgb(124, 10, 3);
        }
      }

      .settlement-btn {
        width: 506px;
        height: 52px;
        line-height: 52px;
        background: #7c0a03;
        border-radius: 12px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #ffffff;
        cursor: pointer;
        margin-top: 20px;
        user-select: none;
      }
    }
  }

  .food-box-right {
    width: 179px;
    height: 986px;
    box-sizing: border-box;
    padding: 24px 0;
    border-left: 1px solid #f4f4f4;
    transition: all 1s !important;

    position: relative;

    .lock-mask {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 20;
      display: flex;
      align-items: center;
      justify-content: center;

      .lock-content {
        background: #ffffff;
        border-radius: 12px;
        padding: 24px 16px;
        display: flex;
        flex-direction: column;
        align-items: center;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

        .lock-text {
          font-size: 16px;
          color: #333333;
          margin-bottom: 12px;
          font-weight: 700;
        }

        .unlock-btn {
          width: 100px;
          height: 36px;
          line-height: 36px;
          text-align: center;
          background: #ffffff;
          border: 1px solid #7c0a03;
          color: #7c0a03;
          border-radius: 12px;
          cursor: pointer;
        }

        .unlock-btn:hover {
          background: #7c0a03;
          color: #ffffff;
        }
      }
    }

    .button-list {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      height: 938px;

      .button-item-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;

        .button-item {
          width: 120px;
          height: 48px;
          line-height: 48px;
          border: 1px solid #333333;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #333333;
          cursor: pointer;
        }

        .button-item:hover {
          border-color: rgb(124, 10, 3);
          color: rgb(124, 10, 3);
        }

        .button-item-disabled {
          border-color: #d9d9d9 !important;
          color: #bfbfbf !important;
          cursor: not-allowed !important;
        }

        .button-item-disabled:hover {
          border-color: #d9d9d9 !important;
          color: #bfbfbf !important;
        }

        .button-item-active {
          display: flex;
          align-items: center;
          justify-content: center;

          width: 120px;
          height: 48px;
          line-height: 48px;
          border-radius: 12px;
          font-size: 18px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #ffffff;
          cursor: pointer;
          background: rgb(124, 10, 3);
          border: none;

          > img {
            flex-shrink: 0;
            width: 20px;
            height: 20px;
            margin-left: 10px;
          }
        }
      }
    }
  }

  .no-data-box {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 170px;
    margin-top: 300px;
    width: 100%;
  }
}
</style>
